package com.hmall.gateway.filters;

import cn.hutool.core.text.AntPathMatcher;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.config.JwtProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.file.Path;
import java.util.List;

@Component
@RequiredArgsConstructor //自动为final生成构造函数
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    //注入配置类--放行的路径参数
    private final AuthProperties authProperties;

    private final JwtTool jwtTool;

    //匹配器，用来匹配authProperties里面的路径--yam配置格式
    private final AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取用户信息request
        ServerHttpRequest request = exchange.getRequest();
        //2.判断是否需要做登录拦截
        if (isExclude(request.getPath().toString())){
            //放行
            return chain.filter(exchange);
        }
        //3.获取token
        String token=null;
        List<String> headers = request.getHeaders().get("authorization");
        if (headers != null && !headers.isEmpty()){
            token=headers.get(0);
        }
        //4.校验并解析token
        Long userId=null;
        try {
            //获取用户id
             userId = jwtTool.parseToken(token);
        }catch (Exception e){
            //拦截，设置401状态码
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //中止响应
            return response.setComplete();
        }
        //5.保存token到请求头中传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                .build();
        //6.放行
        return chain.filter(swe);
    }

    /**
     * 判断是否是放行的路径
     * @param Path
     * @return
     */
    private boolean isExclude(String Path) {
        for (String  pathPattern: authProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern, Path)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
